import React, { useContext } from "react";
import { useReducer } from "react";
let globalContext = React.createContext();
function One() {
    let {state,disPath}= useContext(globalContext);
    return (
        <div>
            <h1>子组件一</h1>
            <div>购物车数量：{state.num}</div>
            <button onClick={()=>{
                disPath({
                    type:"ADD",
                    num:10
                })
            }}>+</button>
        </div>
    )
}


function Two() {
    let {state,disPath}= useContext(globalContext);
    return (
        <div>
            <h2>子组件二</h2>
            <div>购物车数量：{state.num}</div>
            <button onClick={()=>{
                disPath({
                    type:"REDUCE",
                    num:5
                })
            }}>-</button>
        </div>
    )
}
// 处理状态的reducer 处理后返回新的状态
let reducer = (state,action)=>{
    switch(action.type){
        case "ADD":
            let newState = {...state};
            newState.num+=action.num;
            return newState;
        case "REDUCE":
            let newStates = {...state};
            newStates.num-=action.num;
            return newStates;
        default :
            return state
    }
}
// 初始化状态
let initState = {
    num:0,
    msg:"好好学习",
    title:"啦啦啦啦"
}
function App() {
    let [state,disPath] = useReducer(reducer,initState);
    return (
        <div>
            <globalContext.Provider value={{
                state:state,
                disPath:disPath
            }}>
                <One></One>
                <Two />
            </globalContext.Provider>
        </div>
    )
}


export default App;